package algorithm;

import java.math.BigDecimal;

public class Recursion {
    /**
     * 计算每年利润
     * @param capital 本金
     * @param year 年限
     * @param rate 年利率
     * @return
     */
    public static double calculate(double capital, int year,double rate) {
        if (year == 1) {
            return capital * rate + capital;
        }
        double lastYearCapital = calculate(capital, --year, rate);
        System.out.println("year: " + year + " capital:" + lastYearCapital);
        return lastYearCapital * rate + lastYearCapital;
    }

    public BigDecimal calculate(BigDecimal bonus, BigDecimal rate, int year) {
        if (year == 1) {
            return bonus.add(bonus.multiply(rate));
        }
        bonus = calculate(bonus, rate, year - 1);
        bonus = bonus.add(bonus.multiply(rate));
        return bonus;
    }

    public static void main(String[] args) {
        Recursion recursion = new Recursion();
        System.out.println(recursion.calculate(new BigDecimal("10000"), new BigDecimal("0.01"), 10));
        System.out.println(recursion.calculate(new BigDecimal("10000"), new BigDecimal("0.04"), 10));
        System.out.println(recursion.calculate(new BigDecimal("10000"), new BigDecimal("0.05"), 10));
        System.out.println(recursion.calculate(new BigDecimal("10000"), new BigDecimal("0.08"), 10));
    }
}
